package com.useeinfo.oa.modules.base.dao;

import com.useeinfo.framework.extend.dao.CrudDao;
import com.useeinfo.framework.sugar.data.QueryParam;
import com.useeinfo.framework.sugar.data.QueryUtils;
import com.useeinfo.framework.sugar.tools.DateTimeUtils;
import com.useeinfo.framework.sugar.tools.StringConverters;
import com.useeinfo.oa.modules.base.entity.Facility;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import java.util.*;

/**
 * @Auther: bin.liu
 * @Date: 2018/12/4 18:49
 * @Description: 设备管理dao
 */
@Repository("facilityDao")
public class FacilityDao implements CrudDao<Facility> {

    private final static Logger logger = LoggerFactory.getLogger(FacilityDao.class);

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public Map<String, Object> getSearchCondition(Map<String, String> queryHash){
        Map<String, Object> conditionHash = new HashMap<>();

        conditionHash.put("f.deleteStatus = ?{paramIndex} ", false);
        if (queryHash == null || queryHash.size() == 0) {
            return conditionHash;
        }
        String likeName = queryHash.get("likeName");
        if (!StringUtils.isEmpty(likeName)) {
            conditionHash.put("(f.name like ?{paramIndex}) ", "%" + likeName + "%");
        }
        String name = queryHash.get("name");
        if (!StringUtils.isEmpty(name)) {
            conditionHash.put("(f.name = ?{paramIndex}) ", name);
        }
        String likeCode = queryHash.get("likeCode");
        if (!StringUtils.isEmpty(likeCode)) {
            conditionHash.put("(f.code like ?{paramIndex}) ", "%" + likeCode + "%");
        }
        String code = queryHash.get("code");
        if (!StringUtils.isEmpty(code)) {
            conditionHash.put("(f.code = ?{paramIndex}) ", code);
        }
        String serialCode = queryHash.get("serialCode");
        if (!StringUtils.isEmpty(serialCode)) {
            conditionHash.put("(f.serialCode = ?{paramIndex}) ", serialCode);
        }
        String likeSerialCode = queryHash.get("likeSerialCode");
        if (!StringUtils.isEmpty(likeSerialCode)) {
            conditionHash.put("(f.serialCode like ?{paramIndex}) ", "%" + likeSerialCode + "%");
        }
        String qrCode = queryHash.get("qrCode");
        if (!StringUtils.isEmpty(qrCode)) {
            conditionHash.put("(f.qrCode = ?{paramIndex}) ", qrCode);
        }
        String codeOrQRCode = queryHash.get("codeOrQRCode");
        if (!StringUtils.isEmpty(codeOrQRCode)) {
            conditionHash.put("(f.qrCode = ?{paramIndex} or f.code = ?{paramIndex}) ", codeOrQRCode);
        }
        String likeSerialNum = queryHash.get("likeSerialNum");
        if (!StringUtils.isEmpty(likeSerialNum)) {
            conditionHash.put("(f.serialNum like ?{paramIndex}) ", "%" + likeSerialNum + "%");
        }
        String serialNum = queryHash.get("serialNum");
        if (!StringUtils.isEmpty(serialNum)) {
            conditionHash.put("(f.serialNum = ?{paramIndex}) ", serialNum);
        }
        String enterpriseId = queryHash.get("enterpriseId");
        if (!StringUtils.isEmpty(enterpriseId)) {
            conditionHash.put("(f.enterprise.id = ?{paramIndex}) ", StringConverters.ToLong(enterpriseId));
        }
        String enterpriseIds = queryHash.get("enterpriseIds");
        if (!StringUtils.isEmpty(enterpriseIds)) {
            conditionHash.put("(f.enterprise.id in ("+enterpriseIds+") and 1 = ?{paramIndex}) ", 1);
        }
        String facilityGroupId = queryHash.get("facilityGroupId");
        if (!StringUtils.isEmpty(facilityGroupId)) {
            conditionHash.put("(f.facilityGroup.id = ?{paramIndex}) ", StringConverters.ToLong(facilityGroupId));
        }
        String facilityGroup = queryHash.get("facilityGroup");
        if (!StringUtils.isEmpty(facilityGroup)) {
            conditionHash.put("(f.facilityGroup.facilityGroupName = ?{paramIndex}) ", facilityGroup);
        }
        String facilityCatId = queryHash.get("facilityCatId");
        if (!StringUtils.isEmpty(facilityCatId)) {
            conditionHash.put("(f.facilityCat.id = ?{paramIndex}) ", StringConverters.ToLong(facilityCatId));
        }
        String facilityCatName = queryHash.get("facilityCatName");
        if (!StringUtils.isEmpty(facilityCatName)) {
            conditionHash.put("(f.facilityCat.catName like ?{paramIndex}) ", "%" + facilityCatName + "%");
        }
        String rootCatName = queryHash.get("rootCatName");
        if (!StringUtils.isEmpty(rootCatName)) {
            conditionHash.put("(f.facilityCat.catName like ?{paramIndex}) ", "%" + facilityCatName + "%");
        }
        String parentId = queryHash.get("parentId");
        if (!StringUtils.isEmpty(parentId)) {
            conditionHash.put("(f.parentId = ?{paramIndex}) ", StringConverters.ToLong(parentId));
        }
        String relationId = queryHash.get("relationId");//关联设备ID 查询与该设备ID关联的设备
        String relationParentId = queryHash.get("relationParentId");
        if (!StringUtils.isEmpty(relationId)) {
            if(!StringUtils.isEmpty(relationParentId)){
                //该设备有主设备（父级）
                conditionHash.put("(f.parentId = ?{paramIndex} or f.id = "+relationParentId+") ", StringConverters.ToLong(relationId));
            }else{
                //该设备无主设备（父级）
                conditionHash.put("(f.parentId = ?{paramIndex}) ", StringConverters.ToLong(relationId));
            }
        }
        String facilityCatIds = queryHash.get("facilityCatIds");
        if (!StringUtils.isEmpty(facilityCatIds)) {
            conditionHash.put("(f.facilityCat.id in ("+facilityCatIds+") and 1=?{paramIndex}) ", 1);
        }
        String areaId = queryHash.get("areaId");
        if (!StringUtils.isEmpty(areaId)) {
            conditionHash.put("(f.area.id = ?{paramIndex}) ", StringConverters.ToLong(areaId));
        }
        String areaName = queryHash.get("areaName");
        if (!StringUtils.isEmpty(areaName)) {
            conditionHash.put("(f.area.areaName like ?{paramIndex}) ", "%" + areaName + "%");
        }
        String ids = queryHash.get("ids");
        if (StringUtils.isNotEmpty(ids)) {
            String idsSub = ids.substring(ids.indexOf("[") + 1, ids.lastIndexOf("]"));
            String[] idsArr = idsSub.split(",");
            List<Long> idsList = arrStr2LongList(idsArr);
            if (CollectionUtils.isNotEmpty(idsList)) {
                conditionHash.put("(f.id in (?{paramIndex})) ", idsList);
            }
        }

        String searchParam = queryHash.get("searchParam");
        if (!StringUtils.isEmpty(searchParam)) {
            conditionHash.put("(f.name like '%"+searchParam+"%' or f.code like ?{paramIndex}) ", "%" + searchParam + "%");
        }
        String beforeCreateDate = queryHash.get("beforeCreateDate");
        if (StringUtils.isNotBlank(beforeCreateDate)) {
            conditionHash.put("f.createDate > ?{paramIndex} ", DateTimeUtils.parse("yyyy-MM-dd HH:mm:ss",beforeCreateDate));
        }
        return conditionHash;
    }

    /**
     * String[]转List<Long>
     * @param arrStr
     * @return
     */
    public List<Long> arrStr2LongList(String[] arrStr) {
        List<Long> longList = new ArrayList<>();
        for (String str : arrStr) {
            longList.add(StringConverters.ToLong(str.trim()));
        }

        return longList;
    }


    /**
     * 获取总记录数
     */
    @Override
    public Long totalRecord(Map<String, String> queryHash){
        Map<String, Object> conditions = getSearchCondition(queryHash);
        TypedQuery<Long> typedQuery = QueryUtils.getTypedQueryByCondition("select count(f) from Facility f ", conditions, entityManager, Long.class);
        return typedQuery.getSingleResult();
    }

    /**
     * 分页列表
     */
    @Override
    public List<Facility> findList(QueryParam queryParam){
        String sqlInfo = queryParam.joinJPQL("select f from Facility f ", "order by f.id desc ");
        Map<String, Object> conditions = getSearchCondition(queryParam.getSqlMap());
        TypedQuery<Facility> typedQuery = QueryUtils.getTypedQueryByCondition(sqlInfo, conditions, entityManager, Facility.class);
        return queryParam.findPageList(typedQuery);
    }

    /**
     * id获取记录
     */
    @Override
    public Facility findModel(Long id){
        return entityManager.find(Facility.class, id);
    }

    /**
     * 增加记录
     */
    @Override
    public Integer add(Facility facility){
        facility.setCreateDate(new Date());
        entityManager.persist(facility);
        logger.info("FacilityDaoImpl添加facility成功！");
        return 1;
    }

    /**
     * 修改记录
     */
    @Override
    public Integer update(Facility facility){
        facility.setUpdateDate(new Date());
        entityManager.merge(facility);
        return 1;
    }

    /**
     * 删除记录
     */
    @Override
    public Integer delete(Long id){
        Facility facility = entityManager.find(Facility.class, id);
        entityManager.remove(facility);
        return 1;
    }

    /**
     * 删除记录 - 逻辑删除
     */
    @Override
    public Integer deleteLogic(Facility facility){
        facility.setDeleteStatus(true);
        return 1;
    }

    public List<Object[]> getFacilityCountListGroupByCat(String enterpriseIds) {
        String sql = "SELECT root_cat_id,COUNT(*) FROM facility WHERE delete_status = false and enterprise_id in ("+enterpriseIds+") GROUP BY root_cat_id";
        logger.info("sql语句为：" + sql);
        Query query = this.entityManager.createNativeQuery(sql);
        List<Object[]> queryResultList = query.getResultList();
        return queryResultList;
    }

}
